#include "control_api.h"
#include "device/device_manager.h"
#include "logger.h"
#include <stdlib.h>
#include <string.h>

// 全局设备管理器实例
static device_manager_t *g_device_manager = NULL;

// 设置全局设备管理器
void control_api_set_device_manager(device_manager_t *device_mgr) {
    g_device_manager = device_mgr;
}

// 执行设备控制
int control_api_execute_device_control(control_context_t *context) {
    if (!context || !g_device_manager) {
        return ERROR_INVALID_PARAM;
    }

    // 从控制上下文中提取设备控制参数
    json_t *control_params = context->request.headers; // 假设控制参数在headers中

    const char *node = json_string_value(json_object_get(control_params, "node"));
    const char *group = json_string_value(json_object_get(control_params, "group"));
    const char *tag = json_string_value(json_object_get(control_params, "tag"));
    json_t *value = json_object_get(control_params, "value");

    if (!node || !group || !tag || !value) {
        LOG_ERROR("Missing required control parameters: node, group, tag, value");
        return ERROR_INVALID_PARAM;
    }

    // 创建控制请求
    control_request_t control_request;
    memset(&control_request, 0, sizeof(control_request_t));
    control_request.node = strdup(node);
    control_request.group = strdup(group);
    control_request.tag = strdup(tag);
    control_request.value = json_deep_copy(value);

    // 执行控制
    control_response_t *response = device_manager_write_tag(g_device_manager, &control_request);

    // 清理请求
    free(control_request.node);
    free(control_request.group);
    free(control_request.tag);
    json_decref(control_request.value);

    if (!response) {
        LOG_ERROR("Device control failed: no response");
        return ERROR_API_CALL;
    }

    int result = (response->error == 0) ? SUCCESS : ERROR_API_CALL;

    // 记录控制结果
    if (response->error == 0) {
        LOG_INFO("Device control successful: %s.%s.%s", node, group, tag);
    } else {
        LOG_ERROR("Device control failed: %s.%s.%s, error: %d, message: %s",
                  node, group, tag, response->error, response->message ? response->message : "unknown");
    }

    // 清理响应
    if (response->message) {
        free(response->message);
    }
    free(response);

    return result;
}

// 异步执行控制
int control_api_execute_async(control_context_t *context, control_callback_t callback) {
    if (!context || !callback) {
        return ERROR_INVALID_PARAM;
    }

    // 简化实现：在线程中执行同步控制
    // 实际应该使用线程池或异步IO

    // 创建线程数据
    struct {
        control_context_t *context;
        control_callback_t callback;
    } thread_data;

    thread_data.context = context;
    thread_data.callback = callback;

    // 创建线程执行控制
    pthread_t thread;
    if (pthread_create(&thread, NULL, control_execution_thread, &thread_data) != 0) {
        return ERROR_THREAD_CREATE;
    }

    pthread_detach(thread);

    return SUCCESS;
}

static void *control_execution_thread(void *arg) {
    struct {
        control_context_t *context;
        control_callback_t callback;
    } *thread_data = (typeof(thread_data))arg;

    // 执行控制
    int result = control_api_execute_device_control(thread_data->context);

    // 创建模拟响应
    control_response_t *response = control_response_create();
    if (response) {
        response->status_code = (result == SUCCESS) ? 200 : 500;
        if (result != SUCCESS) {
            response->error_msg = strdup("Control execution failed");
        }
    }

    // 调用回调
    thread_data->callback(thread_data->context, response);

    // 清理
    if (response) {
        control_response_free(response);
    }

    return NULL;
}
